import {
  getDate,
  sessionList,
  siteLockStatus,
  cancelReserve,
  unsubscribeOrder,
  siteReserve
} from '../../api/index'
import {
  getYMDHMS
} from '../../utils/util'
Page({

  /* 页面的初始数据 */
  data: {
    itemId: '',
    cqid: '',
    xmid: '',
    daysCount: '',
    title: '',
    maxDay: '',
    time: [],
    Date: '',
    timeList: [],
    list: [],
    siteIds: [],
    siteId: '',
    reserveForm: [],
    price: 0,
    status: '',
    reserveAndOrderId: '',
    ghcd: false,
    nowDate: getYMDHMS(new Date()).slice(0, 10)
  },
  siteReserve() {
    siteReserve({
      param: {
        siteId: this.data.siteIds[0]
      }
    }).then(res => {
      this.setData({
        reserveAndOrderId: res.record.id
      })
    })
  },
  delXZ(e) {
    let num = e.currentTarget.dataset.index
    var list = this.data.list
    let siteIds = this.data.siteIds
    let reserveForm = this.data.reserveForm
    reserveForm.splice(num, 1)
    siteIds.splice(num, 1)
    for (let i = 0; i < list.length; i++) {
      for (let s = 0; s < list[i].sites.length; s++) {
        if (siteIds.length > 0 && siteIds.indexOf(list[i].sites[s].id) != -1) {
          list[i].sites[s].Active = true
        } else {
          list[i].sites[s].Active = false
        }
      }
    }
    this.setData({
      siteIds,
      reserveForm,
      list
    })
  },

  // 点击选择场区
  // clickItem(e) {
  //   if (this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status != 0) return
  //   var list = this.data.list
  //   for (let i = 0; i < list.length; i++) {
  //     for (let s = 0; s < list[i].sites.length; s++) {
  //       if (e.currentTarget.dataset.id == list[i].sites[s].id) {
  //         if (!list[i].sites[s].Active == false) {
  //           this.setData({ price: 0, itemId: '' })
  //         } else {
  //           this.setData({ price: e.currentTarget.dataset.price, itemId: e.currentTarget.dataset.id })
  //         }
  //         list[i].sites[s].Active = !list[i].sites[s].Active
  //       } else {
  //         list[i].sites[s].Active = false
  //       }
  //     }
  //   }
  //   this.setData({ list })
  // },
  cancelReserveBtn() {
    let that = this
    if (this.data.status === '1' || this.data.status === '4') {
      cancelReserve({
        param: {
          reserveAndOrderId: this.data.reserveAndOrderId
        }
      }).then(res => {
        if (res.errorCode === '000000') {
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 1000,
            success(res) {
              setTimeout(() => {
                that.setData({
                  reserveForm: [],
                  siteIds: [],
                  status: ''
                })
                that.sessionList()
              }, 100);
            }
          })
        }
      })
    } else if (this.data.status === '2' || this.data.status === '5') {
      unsubscribeOrder({
        param: {
          reserveAndOrderId: this.data.reserveAndOrderId
        }
      }).then(res => {
        if (res.errorCode === '000000') {
          wx.showToast({
            title: '退订成功',
            icon: 'success',
            duration: 1000,
            success(res) {
              setTimeout(() => {
                that.setData({
                  reserveForm: [],
                  siteIds: [],
                  status: ''
                })
                that.sessionList()
              }, 100);
            }
          })
        }
      })
    }
  },
  siteLockStatusb() {
    let that = this
    siteLockStatus({
      param: {
        type: 1,
        projectId: this.data.xmid,
        siteIds: this.data.siteIds
      }
    }).then(res => {
      if (res.errorCode === '000000') {
        wx.showToast({
          title: '解锁成功',
          icon: 'success',
          duration: 1000,
          success(res) {
            that.setData({
              reserveForm: [],
              siteIds: [],
              status: ''
            })
            that.sessionList()
          }
        })
      }
    })
  },
  siteLockStatus() {
    let that = this
    siteLockStatus({
      param: {
        type: 0,
        projectId: this.data.xmid,
        siteIds: this.data.siteIds
      }
    }).then(res => {
      if (res.errorCode === '000000') {
        wx.showToast({
          title: '锁场成功',
          icon: 'success',
          duration: 1000,
          success(res) {
            that.setData({
              reserveForm: [],
              siteIds: [],
              status: ''
            })
            that.sessionList()
          }
        })
      }
    })
  },
  clickItem(e) {
    var list = this.data.list
    let siteIds = this.data.siteIds
    let reserveForm = this.data.reserveForm
    if (this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status != 0) {
      if (this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status < 6 && !this.data.ghcd) {
        if (this.data.status === this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status && this.data.status == 3) {
          console.log(22)
          let pd = true
          for (let num = 0; num < reserveForm.length; num++) {
            if (reserveForm[num].id === e.currentTarget.dataset.id && reserveForm.length > 0) {
              reserveForm.splice(num, 1)
              siteIds.splice(num, 1)
              pd = false
            }
          }
          if (pd) {
            siteIds.push(e.currentTarget.dataset.id)
            reserveForm.push(e.currentTarget.dataset)
          }
        } else {
          siteIds = []
          reserveForm = []
          siteIds.push(e.currentTarget.dataset.id)
          reserveForm.push(e.currentTarget.dataset)
        }
        this.setData({
          status: this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status
        })
        this.setData({
          siteIds,
          reserveForm
        })
        if (this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status != 3) {
          this.siteReserve()
        }
      }
    } else {
      if (this.data.status != '0') {
        siteIds = []
        reserveForm = []
        siteIds.push(e.currentTarget.dataset.id)
        reserveForm.push(e.currentTarget.dataset)
        this.setData({
          status: this.data.list[e.currentTarget.dataset.f].sites[e.currentTarget.dataset.z].status
        })

      } else if (siteIds.length === 0) {
        siteIds.push(e.currentTarget.dataset.id)
        reserveForm.push(e.currentTarget.dataset)
      } else {
        let pd = true
        for (let num = 0; num < reserveForm.length; num++) {
          if (reserveForm[num].id === e.currentTarget.dataset.id && reserveForm.length > 0) {
            reserveForm.splice(num, 1)
            siteIds.splice(num, 1)
            pd = false
          }
        }
        if (pd) {
          siteIds.push(e.currentTarget.dataset.id)
          reserveForm.push(e.currentTarget.dataset)
        }
      }
      this.setData({
        siteIds,
        reserveForm
      })
    }


    for (let i = 0; i < list.length; i++) {
      for (let s = 0; s < list[i].sites.length; s++) {
        if (siteIds.length > 0 && siteIds.indexOf(list[i].sites[s].id) != -1) {
          list[i].sites[s].Active = true
        } else {
          list[i].sites[s].Active = false
        }
      }
    }
    // let price = 0
    // reserveForm.forEach(em => {
    //   price = price + em.price 
    // })
    this.setData({
      list
    })
  },

  // 获取场次列表
  sessionList() {
    sessionList({
      userId: wx.getStorageSync('userId'),
      param: {
        areaId: this.data.cqid,
        day: this.data.Date,
        projectId: this.data.xmid
      }
    }).then(res => {
      for (let i = 0; i < res.recordList.length; i++) {
        for (let s = 0; s < res.recordList[i].sites.length; s++) {
          res.recordList[i].sites[s].Active = false
        }
      }
      this.setData({
        timeList: res.recordList[0] ? res.recordList[0].sites : [],
        list: res.recordList
      })
    })
  },
  clearList() {
    var list = this.data.list
    for (let i = 0; i < list.length; i++) {
      for (let s = 0; s < list[i].sites.length; s++) {
        list[i].sites[s].Active = false
      }
    }
    this.setData({
      status: '',
      siteIds: [],
      reserveForm: [],
      list
    })
  },

  // 获取最大时间
  getDate() {
    getDate({
      userId: wx.getStorageSync('userId'),
      param: {
        areaId: this.data.cqid,
        projectId: this.data.xmid
      }
    }).then(res => {
      var myDate = new Date()
      let n = String(myDate.getFullYear())
      let y = String(Number(myDate.getMonth()) + 1).length == 1 ? 0 + String(Number(myDate.getMonth()) + 1) : String(Number(myDate.getMonth()) + 1)
      let r = String(Number(myDate.getDate())).length == 1 ? 0 + String(Number(myDate.getDate())) : String(Number(myDate.getDate()))
      this.setData({
        daysCount: res.record.daysCount,
        maxDay: n + '-' + y + '-' + r
      })
      this.get7Days()
    })
  },

  // 提交订单
  submit() {
    if (this.data.siteIds.length === 0) return wx.showToast({
      title: '请选择场次',
      icon: 'none',
      duration: 2000
    })
    // 生成订单
    wx.navigateTo({
      url: `/pages/orderConfirm/index?list=${JSON.stringify(this.data.reserveForm)}&idList=${JSON.stringify(this.data.siteIds)}`
    })
  },
  siteLockStatusc() {
    wx.navigateTo({
      url: `/pages/lock/index?id=${this.data.xmid}`
    })
  },
  edit() {
    if (this.data.siteIds.length === 0) return wx.showToast({
      title: '请选择场次',
      icon: 'none',
      duration: 2000
    })
    // 生成订单
    wx.navigateTo({
      url: `/pages/orderConfirm/edit?siteId=${this.data.siteIds[0]}`
    })
  },
  switchCourt() {
    if (this.data.siteIds.length === 0) return wx.showToast({
      title: '请选择场次',
      icon: 'none',
      duration: 2000
    })
    // 生成订单
    wx.navigateTo({
      url: `/pages/switchCourt/index?siteId=${this.data.siteIds[0]}&title=${this.data.title}&xmid=${this.data.xmid}&cqid=${this.data.cqid}`
    })
  },
  siteFixedReserve() {
    wx.navigateTo({
      url: `/pages/fixedReservation/index?list=${JSON.stringify(this.data.reserveForm)}&xmid=${this.data.xmid}&siteId=${JSON.stringify(this.data.siteIds)}`
    })
  },
  switchCourts() {
    // wx.redirectTo({
    //   url: `/pages/switchCourt/index?siteId=${this.data.siteId}&title=${this.data.title}&xmid=${this.data.xmid}&cqid=${this.data.cqid}&list=${JSON.stringify(this.data.reserveForm)}&idList=${JSON.stringify(this.data.siteIds)}`
    // })
    wx.navigateBack({
      delta: 1
    })
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; // 上一个页面
    prevPage.setData({
      siteId: this.data.siteId,
      title: this.data.siteId,
      xmid: this.data.xmid,
      cqid: this.data.cqid,
      listb: this.data.reserveForm,
      idList: this.data.siteIds
    })
  },

  // 切换日期
  clickTabls(e) {
    if (e.currentTarget.dataset.id == this.data.Date) return
    var arr = []
    for (let i = 0; i < this.data.time.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        this.data.time[i].active = true
      } else {
        this.data.time[i].active = false
      }
      arr.push(this.data.time[i])
    }
    this.setData({
      time: arr,
      list: [],
      Date: e.currentTarget.dataset.id,
      itemId: '',
      reserveForm: [],
      siteIds: [],
      status: ''
    })
    this.sessionList()
  },

  // 获取日期数组
  get7Days() {
    var now = new Date(this.data.maxDay);
    var nowTime = now.getTime();
    var oneDayTime = 24 * 60 * 60 * 1000;
    var dataArr = []
    for (var i = 0; i < this.data.daysCount; i++) {
      //显示周一
      var ShowTime = nowTime + i * oneDayTime;
      //初始化日期时间
      var myDate = new Date(ShowTime);
      var year = myDate.getFullYear();
      var month = myDate.getMonth() + 1;
      if (month < 10) {
        month = '0' + month
      }
      var date = myDate.getDate();
      if (date < 10) {
        date = '0' + date
      }
      var fullDate = year + "-" + month + "-" + date
      var str = "周" + "日一二三四五六".charAt(myDate.getDay());
      let arr = {
        week: str,
        date: date,
        fullDate: fullDate,
        active: false
      }
      dataArr.push(arr)
    }
    dataArr[0].active = true
    dataArr[0].today = true
    this.setData({
      time: dataArr,
      Date: dataArr[0].fullDate
    })
    this.sessionList()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: options.title
    })
    this.setData({
      cqid: options.cqid,
      xmid: options.xmid,
      title: options.title,
      siteId: options.siteId
    })
    this.getDate()
    if (options.ghcd) {
      this.setData({
        ghcd: options.ghcd
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.Date) {
      this.setData({
        reserveForm: [],
        siteIds: [],
        status: ''
      })
      this.sessionList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})